package cn.haoma.base.http;

import com.loopj.android.http.RequestParams;

import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ilioili on 2015/8/5.
 */
public class TokenUtil {
    private static final String KEY = "aasdkafsdk";
    private static Charset UTF8 = Charset.forName("UTF-8");

    public static void setToken(RequestParams requestParams) {
        try {
            Field field = RequestParams.class.getDeclaredField("urlParams");
            field.setAccessible(true);
            ConcurrentHashMap<String, String> urlMap = (ConcurrentHashMap<String, String>) field.get(requestParams);
            requestParams.put("token", getToken(urlMap));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static String getToken(Map<String, String> map) {
        ArrayList keys = new ArrayList(map.size());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (null != entry.getValue()) {
                keys.add(entry.getKey());
            }
        }
        Collections.sort(keys);
        StringBuilder sb = new StringBuilder();
        for (Object key : keys) {
            sb.append(key).append('=').append(String.valueOf(map.get(key))).append('&');
        }
        sb.append("key=").append(KEY);
        return getMD5Str(sb.toString().getBytes(UTF8));
    }

    public static String getMD5Str(byte[] btInput) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
